package com.imooc.search.controller;

import com.imooc.grance.result.GraceJsonResult;
import com.imooc.search.pojo.Stu;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

@RestController
public class Controller {
    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 添加索引
     */
    @GetMapping("createStu")
    public GraceJsonResult createStu() {
        esTemplate.createIndex(Stu.class);
        return GraceJsonResult.ok();
    }

    /**
     * 删除索引
     * @return
     */
    @GetMapping("deleteStu")
    public GraceJsonResult deleteStu() {
        esTemplate.deleteIndex(Stu.class);
        return GraceJsonResult.ok();
    }

    /**
     * 添加数据
     * @return
     */
    @GetMapping("addDoc")
    public GraceJsonResult addDoc() {
//        Stu stu = new Stu(1001L, "levi", 18, 66.6f, "good student");
        Stu stu = new Stu();
        stu.setStuId(1002L);
        stu.setName("levi");
        stu.setAge(18);
        stu.setMoney(66.f);
        stu.setDesc("一个好学生");
        IndexQuery query = new IndexQueryBuilder().withObject(stu).build();
        esTemplate.index(query);
        return GraceJsonResult.ok();
    }

    /**
     * 修改文档数据
     */
    @GetMapping("updateDoc")
    public GraceJsonResult updateDoc() {
        IndexRequest indexRequest = new IndexRequest();

        Map<String, Object> map = new HashMap<>();
        map.put("desc", "hello  world");
        map.put("age", 25);
        indexRequest.source(map);
        UpdateQuery query = new UpdateQueryBuilder()
                .withClass(Stu.class)
                .withId("1001")
                .withIndexRequest(indexRequest)
                .build();
        esTemplate.update(query);
        return GraceJsonResult.ok();
    }

    /**
     * 查询文档数据
     * @param id
     * @return
     */
    @GetMapping("queryDoc")
    public GraceJsonResult queryDoc(String id) {
        GetQuery getQuery = new GetQuery();
        getQuery.setId(id);
        Stu stu = esTemplate.queryForObject(getQuery, Stu.class);
        return GraceJsonResult.ok(stu);
    }

    /**
     * 删除文档数据
     * @param id
     * @return
     */
    @GetMapping("deleteDoc")
    public GraceJsonResult deleteDoc(String id) {
        String str = esTemplate.delete(Stu.class, id);
        return GraceJsonResult.ok();
    }
}
